package com.yiibai.netty.time.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeServerHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		final ByteBuf time = ctx.alloc().buffer(4);  // time协议中需要返回一个32位的整数来表示当前时间
		time.writeInt((int)(System.currentTimeMillis() / 1000L + 2208988800L));
		
		final ChannelFuture future = ctx.writeAndFlush(time);
		future.addListener(new ChannelFutureListener() {
			
			@Override
			public void operationComplete(ChannelFuture arg0) throws Exception {
				assert future == arg0;
				ctx.close();
			}
		});
		//future.addListener(ChannelFutureListener.CLOSE);  // 可以使用预定义的侦听器来简化代码
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
